package hai.com.android_test.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Path;
import android.graphics.RectF;
import android.support.annotation.NonNull;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.ImageView;

import hai.com.android_test.R;


/**
 * 部分圆角ImageView（如下半部分）
 */
public class PartRoundCornerImageView extends ImageView {
    private static final String TAG="PartRoundCorner";
    /*圆角的半径，依次为左上角xy半径，右上角，右下角，左下角*/
    private float[] mRadii = {0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f};
    //private float[] ridii = {0.0f, 0.0f, 0.0f, 0.0f, 20.0f, 20.0f, 15.0f, 15.0f};

    public PartRoundCornerImageView(Context context) {
        this(context,null);
    }

    public PartRoundCornerImageView(Context context, AttributeSet attrs) {
        this(context,attrs,0);
    }

    public PartRoundCornerImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        final TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.PartRoundCornerImageView,defStyleAttr,0);
        float leftTop = typedArray.getDimension(R.styleable.PartRoundCornerImageView_leftTopRadius, 0);
        float rightTop = typedArray.getDimension(R.styleable.PartRoundCornerImageView_rightTopRadius, 0.0f);
        float leftBottom = typedArray.getDimension(R.styleable.PartRoundCornerImageView_leftBottomRadius, 0.0f);
        float rightBottom = typedArray.getDimension(R.styleable.PartRoundCornerImageView_rightBottomRadius, 0.0f);
        mRadii[0] = mRadii[1] = leftTop;
        mRadii[2] = mRadii[3] = rightTop;
        mRadii[4] = mRadii[5] = rightBottom;
        String s=mRadii[0]+","+mRadii[2]+","+mRadii[4]+","+mRadii[6];
        mRadii[6] = mRadii[7] = leftBottom;
        Log.i(TAG, "PartRoundCornerImageView: "+s);
        typedArray.recycle();
    }


    /**
     * 画图
     * by Hankkin at:2015-08-30 21:15:53
     *
     * @param canvas
     */
    protected void onDraw(Canvas canvas) {
        Path path = new Path();
        int w = this.getWidth();
        int h = this.getHeight();  
        /*向路径中添加圆角矩形。radii数组定义圆角矩形的四个圆角的x,y半径。radii长度必须为8*/
        path.addRoundRect(new RectF(0, 0, w, h), mRadii, Path.Direction.CW);
        canvas.clipPath(path);
        super.onDraw(canvas);
    }

    public void setRadii(@NonNull float[] radii) {
        this.mRadii = radii;
        invalidate();
    }
}